package com.ass.nacos.listener;

import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public abstract class AbstractInstanceListener {


    @Autowired
    private NamingService namingService;

    protected abstract String getServiceName();

    //子类实现
    protected abstract void handel(String serviceName, String groupName, String clusters, List<Instance> instances);


    /**
     * 启动消费者 要在spring 容器启动后 进行一些监听 以遍可以从ioc容器中 拿到想要的bean，否则使用@PostConstruct 注解
     * 可能有一些bean 加载不到
     *
     * @param event
     */
    @EventListener(ApplicationPreparedEvent.class)
    public void startConfigListener(ApplicationPreparedEvent event) throws NacosException {
        namingService.subscribe(getServiceName(), item -> {
            if (item instanceof NamingEvent) {
                handel(((NamingEvent) item).getServiceName(),((NamingEvent) item).getGroupName(),
                        ((NamingEvent) item).getClusters(),((NamingEvent) item).getInstances());
            }
        });
    }

}
